package com.example.goods.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author: mtl
 * @Date: 2022/1/19 14:12
 * @Description:
 */
public class MyHttpUtils {

    private static RestTemplate restTemplate = new RestTemplate();;

    public static void main(String[] args) {
        String url = "http://localhost:1000/demo/test1";
        Map<String, String> map = new HashMap<>();
        map.put("userid","1");
        map.put("token","akjsdbaisgdasbjaisdlasdjasal");
        map.put("param","ashdjsdasjl22");

        String urlAuth = urlAuth(map);
        System.out.println(urlAuth);
        System.out.println(url+"?"+urlAuth);
    }

    /**
     * HTTP请求 带请求头
     * @param url 地址
     * @param param 请求参数
     * @param headers 请求头
     * @return
     */
    public String doHttpHeader(String url,Map<String, Object> param,HttpHeaders headers,HttpMethod type){
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
        ResponseEntity<String> result = restTemplate.exchange(url, type, httpEntity, String.class , param);
        return result.getBody();
    }

    /**
     * 生成GET方法 URL链接
     * @param  map2 参数
     * @return 参数=内容 &拼接&拼接
     */
    public static String urlAuth(Map<String,String> map2){
        TreeMap<String, String> treeMap = new TreeMap<>();
        if(map2!=null){
            treeMap.putAll(map2);
        }
        StringBuilder str = new StringBuilder();
        for (Map.Entry<String,String> entry: treeMap.entrySet()){
            str.append("&" +entry.getKey() + "=" + String.valueOf(entry.getValue()));
        }
        return str.substring(1);
    }

}
